import 'dart:async';
import 'dart:io';

import 'package:flutter_sound/flutter_sound.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart' show Level;

class JsAudioPlay {
  static final JsAudioPlay _instance = JsAudioPlay._internal();
  JsAudioPlay._internal();
  factory JsAudioPlay() => _instance;

  FlutterSoundPlayer? _playerModule;
  Timer? _playerSubscription;
  String _lastPath = "";
  int _playDuration = 0;
  Function(bool isFinish, int s)? _lastCallback;

  init() async {
    _playerModule = FlutterSoundPlayer();
    await _playerModule?.openPlayer();
    await _playerModule?.setSubscriptionDuration(const Duration(seconds: 1));

    _playerModule?.setLogLevel(Level.error);
  }

  void resetCallback(String path, Function(bool isFinish, int s) callback) {
    if (_lastPath == path && true == _playerModule?.isPlaying) {
      _lastCallback = callback;
    }
  }

  ///开始播放，这里做了一个播放状态的回调
  void startPlayer(String path, Function(bool isFinish, int s) callback) async {
    try {
      callback(true, -1);
      if (path.isEmpty) return;

      if (_lastPath == path && true == _playerModule?.isPlaying) {
        _lastPath = "";
        stopPlayer();
        return;
      }
      _lastPath = path;

      if (await _fileExists(path)) {
        if (true == _playerModule?.isPlaying) {
          await stopPlayer();
        }
        _lastCallback = callback;
        _lastCallback?.call(false, 0);
        _playDuration = 0;

        await _playerModule?.startPlayer(
            fromURI: path,
            codec: Codec.aacADTS,
            sampleRate: 44000,
            whenFinished: () {
              stopPlayer();
            });

        _playerSubscription = Timer.periodic(const Duration(seconds: 1), (timer) {
          _lastCallback?.call(false, _playDuration);
          _playDuration++;
        });
        //监听播放进度
      }
    } catch (e) {
      e.printError();
      stopPlayer();
    }
  }

  /// 结束播放
  stopPlayer() async {
    _lastCallback?.call(true, -1);
    _lastCallback = null;
    try {
      await _playerModule?.stopPlayer();
    } catch (e) {
      e.printError();
    }
    try {
      _playerSubscription?.cancel();
    } catch (_) {}
    _playerSubscription = null;
  }

  /// 释放播放器
  releaseFlauto() async {
    await stopPlayer();
    try {
      await _playerModule?.closePlayer();
    } catch (e) {
      e.printError();
    }
    _playerModule = null;
  }

  /// 判断文件是否存在
  Future<bool> _fileExists(String path) async {
    return await File(path).exists();
  }
}
